const mysql = require('mysql');
const db = require('../db/index');
const path = require('path');
const fs = require('fs');
const bcrypt = require('bcryptjs');

const myDate = require('../encapsulation/tool/myDate');
const arrMethod = require('../encapsulation/tool/arrMethod');
const addAttendanceSheet = require('../encapsulation/business/attendance/01addAttendanceSheet');
const addOneSalary = require('../encapsulation/business/salary/addOneSalary');

// 修改密码
exports.updatePassword = (req, res) => {
	// 对密码进行加密
	req.body.password = bcrypt.hashSync(req.body.password, 10);
	// 更新密码
	const sql = 'update user set password=? where id=?';
	db.query(sql, [req.body.password, req.body.id], (err, results) => {
		if (err) return res.cc(err);
		res.cc('修改成功', 0);
	})
}

// 上传头像
exports.addUserPhoto = (req, res) => {
	fs.readFile(req.file.path, (err, data)=>{
		if (err) return res.cc('上传失败,请确认是否按照要求上传');
		// 头像命名
		let time = Date.now() + parseInt(Math.random() * 999) + parseInt(Math.random()*2222);
		let extname = req.file.mimetype.split('/')[1]
		let keepname = time + '.' + extname
		// 头像图像
		fs.renameSync(req.file.path, path.join(__dirname, '../static/img/' + keepname));
		res.send({
			status: 0,
			message: '上传成功',
			data: '/img/' + keepname
		})
	})
}

// 添加用户
exports.addUser = (req, res) => {
	const userinfo = req.body;
	// 定义 SQL 语句，查询手机号是否被占用
	const sql = 'select * from user where phone=?';
	db.query(sql, userinfo.phone, (err, results) => {
		if (err) { return res.cc(err) };
		if (results.length > 0) { return res.cc('该手机号已添加') };
		// 判断本次提交是否有身份证号
		if(userinfo.id_number){
			// 查询身份证号是否重复
			const sql = 'select * from user where id_number=?';
			db.query(sql, userinfo.id_number, (err, results) => {
				if (err) { return res.cc(err) };
				if (results.length > 0) { return res.cc('身份证号码重复') };
				// 计算年龄
				userinfo.age = myDate.getAge(myDate.jsDateFormatter(req.body.birth_date).substr(0, 10));
				// 生成默认密码123456，并对其加密
				userinfo.password = '123456';
				userinfo.password = bcrypt.hashSync(userinfo.password, 10);
				// 将添加到 user 表里
				const sql = 'insert into user set ?';
				db.query(sql, userinfo, (err, results) => {
					if (err) { return res.cc(err) };
					if (results.affectedRows !== 1) { return res.cc('新增失败') };
					// 获取新增列得id值
					const sql = 'select * from user'
					db.query(sql, (err, results) => {
						if (err) return res.cc(err)
						// 执行一次考勤表
						addAttendanceSheet.addAttendanceSheet()
						// 将员工数据添加到工资表中
						addOneSalary.addOneSalary(results[results.length - 1].id)
						// 红点添加数据
						const reddotBody = {user_id: results[results.length - 1].id}
						// 查询工资条有多少待审批
						const sql = 'select * from salary where s_audit_state=1'
						db.query(sql, (err, results) => {
							if(err)return res.cc(err)
							reddotBody.salary_examine_num = results.length
							// 创建小红点记录
							const sql = 'insert into reddot set ?'
							db.query(sql, reddotBody, (err, results) => {
								if(err) return res.cc(err)
								res.cc('添加员工成功', 0)
							})
						})
					})
				})
			})
		} else {
			// 计算年龄
			userinfo.age = myDate.getAge(myDate.jsDateFormatter(req.body.birth_date).substr(0, 10));
			// 生成默认密码123456，并对其加密
			userinfo.password = '123456';
			userinfo.password = bcrypt.hashSync(userinfo.password, 10);
			// 将添加到 user 表里
			const sql = 'insert into user set ?';
			db.query(sql, userinfo, (err, results) => {
				if (err) { return res.cc(err) };
				if (results.affectedRows !== 1) { return res.cc('新增失败') };
				// 获取新增列得id值
				const sql = 'select * from user'
				db.query(sql, (err, results) => {
					if (err) return res.cc(err)
					// 执行一次考勤表
					addAttendanceSheet.addAttendanceSheet()
					// 将员工数据添加到工资表中
					addOneSalary.addOneSalary(results[results.length - 1].id)
					// 创建小红点记录
					const reddotBody = {user_id: results[results.length - 1].id}
					const sql = 'insert into reddot set ?'
					db.query(sql, reddotBody, (err, results) => {
						if(err) return res.cc(err)
						res.cc('添加员工成功', 0)
					})
				})
			})
		}
	})
}

// 更新用户
exports.updateUser = (req, res) => {
	const sql = 'select * from user where id<>? and (phone=? or id_number=?)';
	db.query(sql, [req.body.id, req.body.phone, req.body.id_number], (err, results)=>{
		if (err) return res.cc(err);
		if (results.length === 2) return res.cc('手机号与身份证重复');
		if (results.length === 1 && results[0].phone === req.body.phone && results[0].id_number === req.body.id_number) return res.cc('手机号与身份证重复');
		if (results.length === 1 && results[0].phone === req.body.phone) return res.cc('手机号重复');
		if (results.length === 1 && results[0].id_number === req.body.id_number) return res.cc('身份证号重复');
		const sql = 'update user set ? where id=?';
		db.query(sql, [req.body, req.body.id], (err, results)=>{
			if(err) return res.cc(err);
			if(results.affectedRows !== 1) return res.cc('更新失败');
			res.cc('更新成功', 0);
		})
	})
};

// 查询用户列表
exports.getUserList = (req, res) => {
	// 获取列表总数
	const sql = 'select count(*) from user where state<3'
	db.query(sql, (err, results) => {
		if (err) return res.cc(err);
		const listNumber = results[0]['count(*)'];
		const sql = 'select * from user where state<3';
		db.query( sql, (err, results) => {
			if (err) return res.cc(err);
			if (results.length === 0) return res.cc('没有相关数据！');
			// 将results中对象的属性提取出来，组成新的数组
			let arr = results.map((item) => {
				return Object.assign(
					{}, 
					{ id: item.id },
					{ name: item.nick_name },
					{ position_id: item.id_position },
					{ phone: item.phone },
					{ entry_date: item.entry_date },
					{ state: item.state },
					{ leave_date: item.leave_date },
					{ department_id: item.id_department1 }
				)
			})
			// 将岗位id替换为岗位名称
			const sql = 'select * from position'
			db.query(sql, (err, results)=>{
				if (err) return res.cc(err);
				for (let i = 0; i < arr.length; i++){
					for(let j = 0; j < results.length ; j++){
						if (arr[i].position_id === results[j].position_id) {
							arr[i].position_name = results[j].position_name
						}
					}
				}
				let positionArr = arr.map((item) => {
					return Object.assign(
						{},
						{ position_id: item.position_id },
						{ position_name: item.position_name }
					)
				})
				positionArr = arrMethod.unique(positionArr, 'position_id')
				// 查询部门信息
				const sql = 'select * from department1 where delete_state=0 and state=0'
				db.query(sql, (err, results) => {
					if (err) return res.cc(err);
					let departmentArr = results.map((item) => {
						return Object.assign(
							{}, 
							{ department_id: item.department1_id },
							{ department_name: item.department1 }
						)
					});
					res.send({
						status: 0,
						message: '获取用户列表成功',
						data: arr,
						departmentArr,
						positionArr,
						listNumber
					})
				})
			})
		})
	})
}

// 通过用户名查询用户列表
exports.getUserName = (req, res) => {
	// 获取列表总数
	const name = '%' + req.query.name + '%';
	const sql = 'select count(*) from user where state<3 and nick_name like ?'
	db.query(sql, name,(err, results) => {
		if (err) return res.cc(err);
		const listNumber = results[0]['count(*)'];
		const sql = 'select * from user where state<3 and nick_name like ?';
		db.query( sql, name, (err, results) => {
			if (err) return res.cc(err);
			if (results.length === 0) return res.cc('没有找到相关数据！');
			// 将results中对象的属性提取出来，组成新的数组
			let arr = results.map((item) => {
				return Object.assign(
					{}, 
					{ id: item.id },
					{ name: item.nick_name },
					{ id_position: item.id_position },
					{ phone: item.phone },
					{ entry_date: item.entry_date },
					{ state: item.state },
					{ leave_date: item.leave_date },
					{ department_id: item.id_department1 }
				)
			})
			// 将岗位id替换为岗位名称
			const sql = 'select * from position'
			db.query(sql, (err, results)=>{
				if (err) return res.cc(err);
				for (let i = 0; i < arr.length; i++){
					const a = results[arr[i].id_position - 1].position;
					arr[i].id_position = a;
				}
				let positionArr = results.map((item) => {
					return Object.assign(
						{},
						{ position_id: item.position_id },
						{ position_name: item.position_name }
					)
				})
				// 查询部门信息
				const sql = 'select * from department1 where delete_state=0 and state = 0'
				db.query(sql, (err, results) => {
					if (err) return res.cc(err);
					let departmentArr = results.map((item) => {
						return Object.assign(
							{}, 
							{ department_id: item.department1_id },
							{ department_name: item.department1 }
						)
					});
					res.send({
						status: 0,
						message: '获取用户列表成功',
						data: arr,
						departmentArr,
						positionArr,
						listNumber
					})
				})
			})
		})
	})
}

// 通过id获取用户详细信息
exports.getUser = (req, res) => {
	// 查询用户列表
	const sql = 'select * from user where state < 3';
	db.query(sql, (err, results) => {
		if (err) return res.cc(err);
		let userArr = results.map(item => {
			return Object.assign(
				{},
				{user_id: item.id},
				{nick_name: item.nick_name}
			)
		});
		let arr = [];
		arr.push(userArr);
		// 查询基本信息
		const sql = 'select * from user where id=?';
		db.query(sql, req.query.id, (err, results) => {
			if (err) return res.cc(err);
			arr.push(results[0]);
			// id查岗位
			const sql = 'select * from position where position_id=?'; 
			db.query(sql, arr[1].id_position, (err, results) => {
				if (err) return res.cc(err);
				arr[1].position_name = results[0].position_name
				// id查一级部门
				const sql = 'select * from department1 where department1_id=?';
				db.query(sql, arr[1].id_department1, (err, results) => {
					if (err) return res.cc(err);
					arr[1].department1_name = results[0].department1
					// 查询保险
					const sql = 'select * from insurance where user_id=? and state=0'
					db.query(sql, req.query.id, (err, results) => {
						if (err) return res.cc(err);
						arr.push(results);
						// id查权限
						const sql = 'select * from authority where authority_id=?';
						db.query(sql, arr[1].id_authority, (err, results) => {
							if (err) return res.cc(err);
							arr[1].authority_name = results[0].a_name
							// 查询考勤信息
							const sql = 'select * from salary where s_user_id=?';
							db.query(sql, req.query.id, (err, results) => {
								if (err) return res.cc(err);
								arr.push(results[results.length-1]);
								// 查询最近一次调休日期
								let toDay = myDate.toDay();
								const sql = 'select * from attendance where (office_status=1 and day_date<=? and user_id=?)';
								db.query(sql, [toDay, req.query.id], (err, results) => {
									if (err) return res.cc(err);
									if ( results.length != 0 ){
										arr[3].last_rest_date = results[results.length-1].day_date
									} else {
										arr[3].last_rest_date = ''
									}
									// id查询二级部门
									if (arr[1].id_department1 === 0) {
										res.send({
											status: 0,
											message: '查询成功',
											data: arr
										})
									} else {
										const sql = 'select * from department2 where department2_id=?';
										db.query(sql, arr[1].id_department2, (err, results) => {
											if (err) return res.cc(err);
											arr[1].department2_name = results[0].department2
											res.send({
												status: 0,
												message: '查询成功',
												data: arr
											})
										})
									};
								})
							})
						})
					})
				})
			})
		})
	})
}

// 添加保险
exports.addInsurance = (req, res) => {
	const obj = req.body;
	// const obj = [
	// 	{ user_id: 11, insurance_date: '2022-8-8', type: '养老保险', account_number: '15912552773', remarks: '这是一条保险记录'},
	// 	{ user_id: 11, insurance_date: '2022-8-10', type: '失业保险', account_number: '15912552773', remarks: '这是一条保险记录'},
	// 	{ user_id: 11, insurance_date: '2022-1-1', type: '医疗保险', account_number: '15912552773', remarks: '这是一条保险记录'}
	// ]
	// 处理数组中对象
	var values = [];
	obj.forEach(function(n, i){
		var _arr = [];
		for(var m in n){
			_arr.push(n[m]);
		}
		values.push(_arr);
	})
	// 批量添加到数据库中
	const sql = "insert into insurance(user_id, insurance_date, type, account_number, remarks) values ?";
	db.query(sql, [values], (err, results) => {
		if (err) { return res.cc(err) };
		res.cc('保险记录成功', 0);
	})
}

// 查询保险
exports.getInsurance = (req, res) => {
	const sql = 'select * from insurance where state=0 and user_id=?';
	db.query(sql, req.body.user_id, (err, results) => {
		if (err) return res.cc(err);
		if (results.length === 0) return res.cc('没有相关数据！');
		res.send({
			status: 0,
			message: '查询数据成功',
			data: results
		})
	})
}

// 删除保险
exports.deleteInsurance = (req, res) => {
	let ids = '';
	// const arr = [1,2,3];
	const arr = req.body;
	// 将 arr 转换为 '1','2','3',
	for(var i = 0; i < arr.length ; i++){
		ids += "'" + arr[i] + "'" + ","
	}
	// 去掉 arr 最后的逗号
	ids = ids.substr(0, ids.length - 1)
	const sql = "update insurance set state=1 where id in(" + ids + ")";
	db.query(sql, (err, results)=>{
		if(err) return res.cc(err);
		res.cc('删除成功' , 0)
	})
}

// 更新保险
exports.updateInsurance = (req, res)=> {
	// 处理 req.body 的数据
	let values = [];
	req.body.forEach(function(n, i){
		values.push([n, n.id]);
	})
	const model_sql = 'update insurance set ? where id=?';
	var sqls = '';
	// 拼接sql语句
	values.forEach((item, index)=>{
		sqls += mysql.format(model_sql, item) + ';'
	})
	db.query(sqls, (err, results)=>{
		if(err) return res.cc(err);
		res.cc('更新成功' , 0);
	})
}

// 上传合同
exports.addPdf = (req, res) => {
	fs.readFile(req.file.path, (err, data)=>{
		if (err) return res.cc('上传失败,请确认是否按照要求上传');
		// 文件命名
		let time = Date.now() + parseInt(Math.random() * 999) + parseInt(Math.random()*2222);
		let extname = req.file.mimetype.split('/')[1]
		let keepname = time + '.' + extname
		// 文件图像
		fs.renameSync(req.file.path, path.join(__dirname, '../static/pdf/' + keepname));
		res.send({
			status: 0,
			message: '上传成功',
			data: '/pdf/' + keepname
		})
	})
}

// 转正 （表单提交）
exports.regularization = (req, res) => {
	const sql = 'update user set ? where id=?';
	db.query(sql, [req.body, req.body.id], (err, results) => {
		if (err) return res.cc(err);
		res.cc('转正成功', 0)
	})
}

// 离职 （表单提交）
exports.leave = (req, res) => {
	const sql = 'update user set ? where id=?';
	db.query(sql, [req.body, req.body.id], (err, results) => {
		if (err) return res.cc(err);
		// 删除离职日期后的考勤调休(公司考勤，部门考勤，个人考勤)
		const sql = 'select * from attendance where day_date>? and user_id=?'
		db.query(sql, [req.body.leave_date, req.body.id], (err, results) => {
			if(err) return res.cc(err)
			if(results.length === 0) return res.cc('离职成功', 0)
			let userAuthority = results
			let userDates = ''
			for(let i = 0 ; i < userAuthority.length ; i++){
				if(i === 0){
					userDates = "'" + userAuthority[i].day_date + "'"
				} else {
					userDates = userDates + ', ' + "'" + userAuthority[i].day_date + "'"
				}
			}
			const sql = 'select * from attendance where day_date>?'
			db.query(sql, req.body.leave_date, (err, results) => {
				if(err) return res.cc(err)
				if(userAuthority.length === results.length){
					// 该员工离职后仅有该员工申请过休息
					const sql = 'delete from attendance where day_date>?'
					db.query(sql, req.body.leave_date, (err, results) => {
						if(err) return res.cc(err)
						const sql = 'delete from department_attendance where day_date>?'
						db.query(sql, req.body.leave_date, (err, results) => {
							if(err) return res.cc(err)
							const sql = 'delete from company_attendance where c_day_date>?'
							db.query(sql, req.body.leave_date, (err, results) => {
								if(err) return res.cc(err)
								res.cc('离职成功', 0)
							})
						})
					})
				} else {
					// 除了该员工，还有其他员工也申请过调休
					const sql = `delete from attendance where user_id=? and day_date in (${userDates})`
					db.query(sql, req.body.id, (err, results) => {
						if(err) return res.cc(err)
						function deleteCompanyAttendance(){
							const sql = `select * from company_attendance where c_day_date in (${userDates})`
							db.query(sql, (err, results) => {
								if(err) return res.cc(err)
								let deleteArr = []
								let updateArr = []
								results.map(item => {
									if(item.c_rest_number === 1){
										deleteArr.push(item)
									} else {
										updateArr.push(item)
									}
								})
								let value = []
								let sqls = ''
								function getUpdateSqls(){
									updateArr.forEach(item => {
										item.c_rest_number = item.c_rest_number - 1
										value.push([item, item.id])
									})
									value.forEach(item => {
										sqls += mysql.format('update company_attendance set ? where id=?', item) + ';'
									})
								}
								if( 0 < deleteArr.length && deleteArr.length < results.length){
									getUpdateSqls()
									db.query(sqls, (err, results) => {
										if(err) return res.cc(err)
										let deleteDates = ''
										for(let i = 0 ; i < deleteArr.length ; i++){
											if(i === 0){
												deleteDates = "'" + deleteArr[i].c_day_date + "'"
											} else {
												deleteDates = deleteDates + ', ' + "'" + deleteArr[i].c_day_date + "'"
											}
										}
										const sql = `delete from company_attendance where c_day_date in (${deleteDates})`
										db.query(sql, (err, results) => {
											if(err) return res.cc(err)
											res.cc('离职成功', 0)
										})
									})
								} else if(deleteArr.length === 0){
									getUpdateSqls()
									db.query(sqls, (err, results) => {
										if(err) return res.cc(err)
										res.cc('离职成功', 0)
									})
								} else {
									let deleteDates = ''
									for(let i = 0 ; i < deleteArr.length ; i++){
										if(i === 0){
											deleteDates = "'" + deleteArr[i].c_day_date + "'"
										} else {
											deleteDates = deleteDates + ', ' + "'" + deleteArr[i].c_day_date + "'"
										}
									}
									const sql = `delete from company_attendance where c_day_date in (${deleteDates})`
									db.query(sql, (err, results) => {
										if(err) return res.cc(err)
										res.cc('离职成功', 0)
									})
								}
							})
						}
						const sql = 'select * from user where id=?'
						db.query(sql, req.body.id, (err, results) => {
							if(err) return res.cc(err)
							const user_department_id = results[0].id_department1
							const sql = `select * from department_attendance where department_id=? and day_date in (${userDates})`
							db.query(sql, user_department_id, (err, results) => {
								if(err) return res.cc(err)
								let deleteArr = []
								let updateArr = []
								results.map(item => {
									if(item.rest_number === 1){
										deleteArr.push(item)
									} else {
										updateArr.push(item)
									}
								})
								let value = []
								let sqls = ''
								function getUpdateSqls(){
									updateArr.forEach(item => {
										item.rest_number = item.rest_number - 1
										value.push([item, item.id])
									})
									value.forEach(item => {
										sqls += mysql.format('update department_attendance set ? where id=?', item) + ';'
									})
								}
								if( 0 < deleteArr.length && deleteArr.length < results.length){
									getUpdateSqls()
									db.query(sqls, (err, results) => {
										if(err) return res.cc(err)
										let deleteDates = ''
										for(let i = 0 ; i < deleteArr.length ; i++){
											if(i === 0){
												deleteDates = "'" + deleteArr[i].day_date + "'"
											} else {
												deleteDates = deleteDates + ', ' + "'" + deleteArr[i].day_date + "'"
											}
										}
										const sql = `delete from department_attendance where department_id=? and day_date in (${deleteDates})`
										db.query(sql, user_department_id, (err, results) => {
											if(err) return res.cc(err)
											deleteCompanyAttendance()
										})
									})
								} else if(deleteArr.length === 0){
									getUpdateSqls()
									db.query(sqls, (err, results) => {
										if(err) return res.cc(err)
										deleteCompanyAttendance()
									})
								} else {
									let deleteDates = ''
									for(let i = 0 ; i < deleteArr.length ; i++){
										if(i === 0){
											deleteDates = deleteArr[i].day_date
										} else {
											deleteDates = deleteDates + ', ' + "'" + deleteArr[i].day_date + "'"
										}
									}
									const sql = `delete from department_attendance where department_id=? and day_date in (${deleteDates})`
									db.query(sql, user_department_id, (err, results) => {
										if(err) return res.cc(err)
										deleteCompanyAttendance()
									})
								}
							})
						})
					})
				}
			})
		})
	})
}

// 查询工资表未提交
exports.getAllSalary = (req, res) => {
	// 处理前端传过来的ids
	let arr = req.query.ids.split('@');
	let ids = '';
	for (var i = 0; i < arr.length; i++) {
		ids += "'" + arr[i] + "'" + ","
	}
	ids = ids.substr(0, ids.length - 1)
	const sql = "select * from salary where s_user_id in(" + ids + ") and s_audit_state<2";
	db.query(sql, (err, results) => {
		if (err) return res.cc(err);
		if (results.length === 0) return res.cc('当前没有可结算的工资条');
		let data = results
		const sql = 'select * from user'
		db.query(sql, (err, results) => {
			if (err) return res.cc(err)
			for(let i = 0; i < results.length; i++){
				for(let j = 0;j< data.length; j++){
					if(results[i].id === data[j].s_user_id){
						data[j].s_user_name = results[i].name
					}
				}
			}
			const sql = 'select * from position'
			db.query(sql, (err, results) => {
				if (err) return res.cc(err)
				for(let i = 0; i < results.length; i++){
					for(let j = 0;j< data.length; j++){
						if(results[i].position_id === data[j].s_position_id){
							data[j].s_position_name = results[i].position_name
						}
					}
				}
				const sql = 'select * from department1'
				db.query(sql, (err, results) => {
					if (err) return res.cc(err)
					for(let i = 0; i < results.length; i++){
						for(let j = 0;j< data.length; j++){
							if(results[i].department1_id === data[j].s_department_id){
								data[j].s_department_name = results[i].department1
							}
						}
					}
					res.send({
						status: 0,
						message: '查询成功',
						data
					})
				})
			})
		})
	})
}

// 保存
exports.saveSalary = (req, res) => {
	// 处理 req.body 的数据
	let arr = [];
	req.body.forEach(function(n, i){
		arr.push([n, n.s_id]);
	})
	const model_sql = 'update salary set ? where s_id=?';
	var sqls = '';
	// 拼接sql语句
	arr.forEach((item, index)=>{
		sqls += mysql.format(model_sql, item) + ';'
	})
	db.query(sqls, (err, results)=>{
		if(err) return res.cc(err);
		res.cc('保存成功' , 0);
	})
}

// 提交
exports.submitSalary = (req, res) => {
	// 处理 req.body 的数据
	let arr = [];
	req.body.forEach(function(n, i){
		n.s_audit_state = 1;
		arr.push([n, n.s_id]);
	})
	const model_sql = 'update salary set ? where s_id=?';
	var sqls = '';
	// 拼接sql语句
	arr.forEach((item, index)=>{
		sqls += mysql.format(model_sql, item) + ';'
	})
	db.query(sqls, (err, results)=>{
		if(err) return res.cc(err);
		const sql = 'select * from salary where s_audit_state=1'
		db.query(sql, (err, results) => {
			if(err)return res.cc(err)
			const sql = `update reddot set salary_examine_num=${results.length}`
			db.query(sql, (err, results) => {
				if(err)return res.cc(err)
				res.cc('提交成功，已通过' , 0)
			})
		})
	})
}

// 查询已提交和审核的内容
exports.getSubmitSalary = (req, res) => {
	const sql = 'select * from salary where s_audit_state>0';
	db.query(sql, (err, results) => {
		if (err) return res.cc(err);
		let data = results
		const sql = 'select * from user'
		db.query(sql, (err, results) => {
			if (err) return res.cc(err)
			for(let i = 0; i < results.length; i++){
				for(let j = 0;j< data.length; j++){
					if(results[i].id === data[j].s_user_id){
						data[j].s_user_name = results[i].name
					}
				}
			}
			const sql = 'select * from position'
			db.query(sql, (err, results) => {
				if (err) return res.cc(err)
				for(let i = 0; i < results.length; i++){
					for(let j = 0;j< data.length; j++){
						if(results[i].position_id === data[j].s_position_id){
							data[j].s_position_name = results[i].position_name
						}
					}
				}
				const sql = 'select * from department1'
				db.query(sql, (err, results) => {
					if (err) return res.cc(err)
					for(let i = 0; i < results.length; i++){
						for(let j = 0;j< data.length; j++){
							if(results[i].department1_id === data[j].s_department_id){
								data[j].s_department_name = results[i].department1
							}
						}
					}
					res.send({
						status: 0,
						message: '查询成功',
						data
					})
				})
			})
		})
	})
}

// 工资审核通过
exports.agreeSalary = (req, res) => {
	// 处理 req.body 的数据
	let arr = [];
	req.body.forEach(function(n, i){
		n.s_audit_state = 2;
		arr.push([n, n.s_id]);
	})
	const model_sql = 'update salary set ? where s_id=?';
	var sqls = '';
	// 拼接sql语句
	arr.forEach((item, index)=>{
		sqls += mysql.format(model_sql, item) + ';'
	})
	db.query(sqls, (err, results)=>{
		if(err) return res.cc(err);
		const sql = 'select * from salary where s_audit_state=1'
		db.query(sql, (err, results) => {
			if(err)return res.cc(err)
			const sql = `update reddot set salary_examine_num=${results.length}`
			db.query(sql, (err, results) => {
				if(err)return res.cc(err)
				res.cc('操作成功，已通过' , 0)
			})
		})
	})
}

// 查看个人历史工资记录
exports.getUserSalary = (req, res) => {
	const sql = 'select * from salary where s_user_id=? and s_audit_state=2';
	db.query(sql, req.query.s_user_id, (err, results) => {
		if (err) return res.cc(err);
		if (results.length === 0) return res.cc('该用户暂无工资条记录')
		let data = results
		const sql = 'select * from user'
		db.query(sql, (err, results) => {
			if (err) return res.cc(err)
			for(let i = 0; i < results.length; i++){
				for(let j = 0;j< data.length; j++){
					if(results[i].id === data[j].s_user_id){
						data[j].s_user_name = results[i].name
					}
				}
			}
			const sql = 'select * from position'
			db.query(sql, (err, results) => {
				if (err) return res.cc(err)
				for(let i = 0; i < results.length; i++){
					for(let j = 0;j< data.length; j++){
						if(results[i].position_id === data[j].s_position_id){
							data[j].s_position_name = results[i].position_name
						}
					}
				}
				const sql = 'select * from department1'
				db.query(sql, (err, results) => {
					if (err) return res.cc(err)
					for(let i = 0; i < results.length; i++){
						for(let j = 0;j< data.length; j++){
							if(results[i].department1_id === data[j].s_department_id){
								data[j].s_department_name = results[i].department1
							}
						}
					}
					res.send({
						status: 0,
						message: '查询成功',
						data
					})
				})
			})
		})
	})
}

// 获取选择框用户下拉列表
exports.getUserSelectList = (req, res) => {
	const sql = 'select * from user where state < 2'
	db.query(sql, (err, results) => {
		if(err) return res.cc(err)
		let arr = results.map(item => {
			return Object.assign(
				{ value: item.id },
				{ label: item.nick_name }
			)
		})
		res.send({
			status: 0,
			message: '查询成功',
			data: arr
		})
	})
}

// 获取徽标信息
exports.getReddot = (req, res) => {
	const sql = 'select * from reddot where user_id=?'
	db.query(sql, req.query.user_id, (err, results) => {
		if(err)return res.cc(err)
		res.send({
			status: 0,
			messgae: '查询成功',
			data: results
		})
	})
}